package com.atguigu.java.ai.langchain4j.store;

import com.atguigu.java.ai.langchain4j.bean.ChatMessagesMy;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * @Author: zhang
 * @Date: 2025/8/30 13:03
 * @Description:
 **/
@Component
public class MongoChatMemoryStore implements ChatMemoryStore {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query query = new Query(criteria);
        ChatMessagesMy chatMessagesMy = mongoTemplate.findOne(query, ChatMessagesMy.class);
        if(chatMessagesMy==null){
            return Collections.emptyList();
        }
        return ChatMessageDeserializer.messagesFromJson(chatMessagesMy.getMessage());
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {

        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query query = new Query(criteria);
        Update update = new Update();
        update.set("message", ChatMessageSerializer.messagesToJson(messages));
        mongoTemplate.upsert(query,update, ChatMessagesMy.class);
    }

    @Override
    public void deleteMessages(Object memoryId) {
        Criteria id = Criteria.where("memoryId").is(memoryId);
        Query query = new Query(id);
        mongoTemplate.remove(query,ChatMessagesMy.class);
    }

}
